/**
 * SelfCtrl.java
 *
 */
package com.navidove.web.manager.ctrl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.navidove.appspotlight.model.bo.SysUser;
import com.navidove.appspotlight.model.service.SysUserService;
import com.navidove.commons.exception.DataDuplicatedException;
import com.navidove.commons.utils.I18NUtil;

/**
 * SelfCtrl
 *
 * @author $Author$
 * @version $Revision$
 * @date $Date$
 * @url $URL$
 */
@Controller
public class SelfCtrl {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	
	@Autowired
	private SysUserService sysUserService;
	
    @ModelAttribute
    public void reset(Model model) {        
        SysUser sysUser = sysUserService.getCurrentSysUser();
        model.addAttribute("sysUser", sysUser);       
    }

	@RequestMapping(value="/home/self/init")
	public String init(Model model) {
		return "home/self_edit";
	}
	
    @ResponseBody
    @RequestMapping("/home/self/save")
    public Map<String, Object> save(Model model, @ModelAttribute("sysUser") SysUser sysUser) {

        String success = I18NUtil.getMsg("dialog.message.data.param.success", I18NUtil.getMsg("button.save"));
        String failure = I18NUtil.getMsg("dialog.message.data.param.failure", I18NUtil.getMsg("button.save"));
        
        Map<String, Object> rtnVal = new HashMap<String, Object>();        
 
        try {
            sysUserService.saveSysUser(sysUser);
            rtnVal.put("message", success);
            rtnVal.put("success", Boolean.TRUE);
            rtnVal.put("data", sysUser.getId());
        } catch (DataDuplicatedException e) {
            logger.error(e.getMessage(),e);
            rtnVal.put("message", I18NUtil.getMsg("dialog.message.param.not.duplicated",
                    I18NUtil.getMsg("system.bo.SysUser.login")));
            rtnVal.put("success", Boolean.FALSE);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            rtnVal.put("message", failure);
            rtnVal.put("success", Boolean.FALSE);
        }

        return rtnVal;
    }    
}
